(use-modules (commonmark)
             (sxml simple))


;; =======
;; HELPERS
;; =======
(define displayln
  (λ (sth)
    (display (simple-format #f "~a\n" sth))))

(define (map* proc lst)
  (cond [(null? lst) '()]
        [(pair? (car lst))
         (cons (map* proc (car lst))
               (map* proc (cdr lst)))]
        [else
         (cons (proc (car lst))
               (map* proc (cdr lst)))]))

(define (stringify* lst)
  (map* (λ (val)
          (cond
           [(number? val) (number->string val)]
           [(string? val) val]
           [else (simple-format #f "~s" val)]))
        lst))


;; =============================
;; LIBRARY INTERFACE ABSTRACTION
;; =============================
(define* (md-file->sxml file-path #:key (encoding "UTF-8"))
  (call-with-input-file file-path
    (λ (port)
      (set-port-encoding! port encoding)
      (md-string->sxml port))))


(define* (md-file->xml-string file-path #:key (encoding "UTF-8"))
  (sxml->xml-string
   (md-file->sxml file-path #:encoding encoding)))


(define* (md-string->sxml input)
  ;; takes a string or a port
  (commonmark->sxml input))


(define* (sxml->xml-file sxml-tree file-path #:key (encoding "UTF-8"))
  (call-with-output-file file-path
    (λ (port)
      (set-port-encoding! port encoding)
      (sxml->xml sxml-tree port))))


(define* (sxml->xml-string sxml-tree)
  (call-with-output-string
    (λ (port)
      (sxml->xml sxml-tree port))))


(define document
  (string-join '("A CommonMark document"
                 "============="
                 ""
                 "1. here is a list"
                 "2. with another item"
                 ""
                 "    this is some code"
                 ""
                 "A regular paragraph")
               "\n"))


;; =============
;; USAGE EXAMPLE
;; =============
(define (main)
  (displayln "read from file")
  (displayln (md-file->xml-string "example.md"))

  (displayln "read from string")
  (displayln (md-string->sxml document))

  (displayln "write to file")
  (displayln (sxml->xml-file (md-string->sxml document) "example.html"))

  (displayln "write to string")
  (displayln (sxml->xml-string (md-string->sxml document))))

(main)
